// 商家信息store
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useMerchantStore = defineStore('merchant', () => {
  // 定义状态
  const merchantId = ref<number | null>(null)
  const merchantName = ref('')
  const merchantLogo = ref('')
  const description = ref('')
  const province = ref('')
  const city = ref('')
  const district = ref('')
  const detail = ref('')
  const balance = ref<number>(0)
  const isLoggedIn = ref(false)
  const merchantToken = ref('')

  // 设置商家信息
  const setMerchantInfo = (info: any) => {
    merchantId.value = info.id
    merchantName.value = info.name || ''
    merchantLogo.value = info.logo || ''
    description.value = info.description || ''
    province.value = info.province || ''
    city.value = info.city || ''
    district.value = info.district || ''
    detail.value = info.detail || ''
    balance.value = info.balance || 0
    isLoggedIn.value = true
  }

  // 设置商家token
  const setMerchantToken = (token: string) => {
    merchantToken.value = token
    isLoggedIn.value = true
  }

  // 更新商家基本信息
  const updateMerchantInfo = (info: any) => {
    if (info.name !== undefined) merchantName.value = info.name
    if (info.description !== undefined) description.value = info.description
    if (info.province !== undefined) province.value = info.province
    if (info.city !== undefined) city.value = info.city
    if (info.district !== undefined) district.value = info.district
    if (info.detail !== undefined) detail.value = info.detail
  }

  // 更新商家Logo
  const updateMerchantLogo = (logo: string) => {
    merchantLogo.value = logo
  }

  // 清除商家信息（登出时使用）
  const clearMerchant = () => {
    merchantId.value = null
    merchantName.value = ''
    merchantLogo.value = ''
    description.value = ''
    province.value = ''
    city.value = ''
    district.value = ''
    detail.value = ''
    balance.value = 0
    isLoggedIn.value = false
    merchantToken.value = ''
  }

  // 完整地址
  const fullAddress = computed(() => {
    return `${province.value}${city.value}${district.value}${detail.value}`
  })

  return {
    merchantId,
    merchantName,
    merchantLogo,
    description,
    province,
    city,
    district,
    detail,
    balance,
    isLoggedIn,
    merchantToken,
    fullAddress,
    setMerchantInfo,
    setMerchantToken,
    updateMerchantInfo,
    updateMerchantLogo,
    clearMerchant
  }
}, {
  persist: true // 持久化存储商家信息
})
